<?php

namespace app\astrologer\controller\v4;

use app\aliyun\controller\AliyunFilterWord;
use app\aliyun\controller\AliyunRtc;
use app\astrologer\controller\AstrAuth;
use app\chat\LiveMessage;
use app\common\cachemodel\consult\AppConsultGift;
use app\common\cachemodel\consult\AppUserConsultGift;
use app\common\cachemodel\UserCoupon;
use app\common\cachemodel\ZhunleUserAccount;
use app\common\cachemodel\ZlCouponAttr;
use app\common\cachemodel\zlcr3\Zlcr3ConsultAccount;
use app\common\cachemodel\ZlcrAstrConsultActiveReplyRecord;
use app\common\cachemodel\ZlcrTag;
use app\common\lib\exception\ApiException;
use app\common\lib\Push;
use app\common\lib\Util;
use app\common\model\User;
use app\zyhsapi\lib\ZyhsPush;
use app\zyhsapi\model\ZyhsConsultAstrData;
use app\zyhsapi\model\ZyhsConsultChatInterceptRecord;
use app\zyhsapi\model\ZyhsConsultChatRecord;
use app\zyhsapi\model\ZyhsConsultChatRecordAstr;
use app\zyhsapi\model\ZyhsConsultChatRecordDetails;
use app\zyhsapi\model\ZyhsConsultChatRtcRecord;
use app\zyhsapi\model\ZyhsConsultChatRtcRecordComment;
use app\zyhsapi\model\ZyhsConsultQuestion;
use app\zyhsapi\model\ZyhsConsultRtcUserBenefits;
use app\zyhsapi\model\ZyhsCoupon;
use app\zyhsapi\model\ZyhsUser;
use app\zyhsapi\model\ZyhsUserAccount;
use app\zyhsapi\model\ZyhsUserCoupon;
use think\Db;
use think\Env;
use think\Exception;
use think\exception\DbException;
use think\response\Json;

class Consult extends AstrAuth
{
    /**
     * 获取 咨询对话 列表
     * @return Json
     * @throws \Exception
     */
    public function getConsultChatList()
    {
        $type = input('type/d', 0);
        $page = input('page/d', 1);
        $limit = input('limit/d', 10);

        if (!in_array($type, [1, 2, 3], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $complete = isset($this->astrInfo['extend']['is_complete_information']) ? 1 : 0;
        $typeIds1 = [];
        if (!$this->astrInfo['uid'] || $complete === 0)
        {
            $pageData = [
                'total' => 0,
                'per_page' => 10,
                'current_page' => 1,
                'last_page' => 1,
                'data' => [],
            ];
        } else
        {
            if ($type === 1)
            {
                $pageData = $zyhsConsultChatRecordAstrModel->pageDataIds($this->astrInfo['id'], $type, 1, 100);
                $typeIds1 = $pageData['data'];
            } else
            {
                $page = $page > 0 ? $page : 1;
                $limit = 50;
                $pageData = $zyhsConsultChatRecordAstrModel->pageDataIds($this->astrInfo['id'], $type, $page, $limit);
                $type1PageData = $zyhsConsultChatRecordAstrModel->pageDataIds($this->astrInfo['id'], 1, 1, 100);
                $typeIds1 = $type1PageData['data'];
            }
            $consultChatList = $zyhsConsultChatRecordAstrModel->batchGetInfoByIds($pageData['data']);
            $consultChatList = $zyhsConsultChatRecordAstrModel->pageDataResert($consultChatList);

            $resList = [];
            foreach ($pageData['data'] as $id)
            {
                $resList[] = $consultChatList[$id];
            }

            $pageData['data'] = $resList;

            if ($type === 1)
            {
                $pageData['total'] = min($pageData['total'], 100);
                $pageData['last_page'] = 1;
            }
        }
        $consultAstrInfo = $this->consultAccountInfo;
        $pageData['work_status'] = $consultAstrInfo['status'] === 1 ? 1 : 0;
        $consultStatus = $consultAstrInfo['consult_status'] === 1 && $consultAstrInfo['level_score'] > -10 ? 1 : 2;
        $pageData['consult_status'] = $consultStatus;
        $pageData['tip'] = $consultStatus === 2 ? '当前账号已被取消接单资格，如有疑问请联系官方。' : '';
        $pageData['newMsg1'] = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 1, $typeIds1) ? 1 : 0;
        $pageData['newMsg2'] = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 2) ? 1 : 0;
        $pageData['newMsg3'] = $zyhsConsultChatRecordAstrModel->getAstrUnreadAllNum($this->astrInfo['id'], 3) ? 1 : 0;

        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 获取 对话详情记录 列表
     * @return Json
     * @throws ApiException
     * @throws DbException
     */
    public function getConsultChatDetailRecord()
    {
        $appType = input('app_type/d', 1);
        $uid = input('uid/d', 0);
        $minId = input('min_id/d', 0);
        if (!$uid || !in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $chatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($this->astrInfo['id'], $appType, $uid);
        if (!$chatId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($chatId);
        if ($astrChatIdInfo && isset($astrChatIdInfo['unread_num']) && $astrChatIdInfo['unread_num'] > 0)
        {   // 未读消息数量 大于0
            $zyhsConsultChatRecordAstrModel->astroSendUpdate($appType, $astrChatIdInfo['uid'], $this->astrInfo['id'], [
                'unread_num' => 0,
            ]);
            if ($astrChatIdInfo['consult_coin'] > 0 || (isset($astrChatIdInfo['is_customer']) && $astrChatIdInfo['is_customer']))
            {
                $msgType = 3;
            } elseif ($astrChatIdInfo['reply_num'] > 0 || $astrChatIdInfo['consult_num'] > 0)
            {
                $msgType = 2;
            } else
            {
                $msgType = 1;
            }
            // 消息已读
            $zyhsConsultChatRecordAstrModel->setAstrUnreadAllNumInc($this->astrInfo['id'], $chatId, $msgType, 2, 0);
        }

        $where = [
            'app_type' => $appType,
            'uid' => $uid,
            'astr_id' => $this->astrInfo['id'],
        ];
        if ($minId > 0)
        {
            $where['id'] = ['<', $minId];
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $pageData = $consultChatRecordDetailsModel->where($where)
            ->order('id desc')
            ->paginate(['page' => 1, 'list_rows' => 15])->toArray();

        krsort($pageData['data']);
        if ($appType === 1)
        {
            $userInfo = (new ZyhsUser())->getInfoById($uid);
            $nickname = $userInfo['nickname'];
        } else
        {
            $userInfo = (new \app\common\model\User())->getUserinfo(['id' => $uid]);

            if (isset($astrChatIdInfo['extend']['user_remark']) && $astrChatIdInfo['extend']['user_remark'])
            {
                $nickname = $astrChatIdInfo['extend']['user_remark'];
            } else
            {
                $nickname = $userInfo['nickname'];
            }
        }
        $pageData['data'] = $consultChatRecordDetailsModel->dataInit($pageData['data']);
        $consultAstrInfo = $this->consultAccountInfo;
        $surplusNum = $pageData['total'] - $pageData['per_page'];

        $delayNum = ($astrChatIdInfo['delay_num'] > 0) ? $astrChatIdInfo['delay_num'] : 0;
        $callDelayNum = ($astrChatIdInfo['call_delay_num'] > 0) ? $astrChatIdInfo['call_delay_num'] : 0;
        $resData = [
            'surplus_num' => max($surplusNum, 0),
            'data' => $consultChatRecordDetailsModel->astrDataListResert($pageData['data'], $this->astrInfo, $userInfo, $appType),
            'num' => $delayNum + $callDelayNum,
            'nickname' => $nickname,
            'consult_status' => $consultAstrInfo['consult_status'] === 1 && $consultAstrInfo['level_score'] > -10 ? 1 : 2,
        ];

        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 咨询消息 已读
     * @return Json
     * @throws \Exception
     */
    public function consultChatMsgRead()
    {
        $appType = input('app_type/d', 1);
        $uid = input('uid/d', 0);
        if (!$uid || !in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $chatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($this->astrInfo['id'], $appType, $uid);
        if ($chatId)
        {
            $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($chatId);

            if ($astrChatIdInfo['unread_num'] > 0)
            {
                $zyhsConsultChatRecordAstrModel->updateData($chatId, $this->astrInfo['id'], ['unread_num' => 0]);

                if ($astrChatIdInfo['consult_coin'] > 0 || (isset($astrChatIdInfo['is_customer']) && $astrChatIdInfo['is_customer']))
                {
                    $msgType = 3;
                } elseif ($astrChatIdInfo['reply_num'] > 0 || $astrChatIdInfo['consult_num'] > 0)
                {
                    $msgType = 2;
                } else
                {
                    $msgType = 1;
                }
                // 消息已读
                $zyhsConsultChatRecordAstrModel->setAstrUnreadAllNumInc($this->astrInfo['id'], $chatId, $msgType, 2, 0);
            }
        }

        return show(config('code.success'), '请求成功');
    }

    /**
     * 发送 咨询对话 信息
     * @return Json
     * @throws \Exception
     */
    public function sendConsultMsg()
    {
        $appType = input('app_type/d', 1);
        $uid = input('uid/d', 0);
        $content = trim(input('content/s', ''));
        if (empty($content) || !in_array($appType, [1, 2], true) || !$uid)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->astrInfo['id'], ['action' => 'astrSendConsultMsg', 'uid' => $uid, 'content' => $content], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (mb_strlen($content) > 200)
        {
            return show(config('code.error'), '最多输入200个字～');
        }
        $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $astrChatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($this->astrInfo['id'], $appType, $uid);
        if (!$astrChatId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($astrChatId);
        if ($astrChatIdInfo['delay_num'] + $astrChatIdInfo['call_delay_num'] <= 0)
        {
            return show(config('code.error'), '当前不可发送消息～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $userChatId = $consultChatIdModel->getChatIdByAstrId($appType, $uid, $this->astrInfo['id']);
        $nowTimw = $this->request->time();
        if (!$userChatId)
        {
            $insertData = [
                'app_type' => $appType,
                'uid' => $uid,
                'astr_id' => $this->astrInfo['id'],
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $userChatId = $consultChatIdModel->SaveData($insertData);
        }
        // 阿里云内容审查
        $res = AliyunFilterWord::checkText($content, 'voice_mic');
        if ($res)
        {
            if ($res['level'] === 'review')
            {
                $interceptTips = (new ZyhsConsultChatRecordDetails())->interceptTips;
                (new ZyhsConsultChatInterceptRecord())->saveData([
                    'type' => 1,
                    'level' => 1,
                    'content_type' => 1,
                    'chat_id' => $userChatId,
                    'user_id' => $this->astrInfo['id'],
                    'content' => $content,
                    'reason' => $res['text'],
                    'create_time' => $this->request->time(),
                ]);
            } elseif ($res['level'] === 'block')
            {
                (new ZyhsConsultChatInterceptRecord())->saveData([
                    'type' => 1,
                    'level' => 2,
                    'content_type' => 1,
                    'chat_id' => $userChatId,
                    'user_id' => $this->astrInfo['id'],
                    'content' => $content,
                    'reason' => $res['text'],
                    'create_time' => $this->request->time(),
                ]);
                return show(430, '发送失败，你所发送的内容中包含敏感信息。 注意不要泄露自己的联系方式和个人信息，以防上当受骗，平台将对你的个人隐私严格保密 。');
            }
        }
        $consultMsgData = [
            'chat_id' => $userChatId,
            'app_type' => $appType,
            'uid' => $uid,
            'astr_id' => $this->astrInfo['id'],
            'type' => 1,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => $content, // 提问问题
            'data_type' => 1,   // 1=>普通消息  2=>图片  3=>语音咨询消息
            'extend' => ['intercept_tips' => isset($interceptTips) ? $res['text'] : ''],  //  语音咨询消息 ｜ 图片信息 | 内容拦截信息
            'pid' => 0, // 待更新
            'create_time' => $nowTimw,
        ];
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $resData = $consultChatRecordDetailsModel->SaveData($userChatId, $consultMsgData);
        if (!$resData)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $consultChatIdDetail = $zyhsConsultChatRecordAstrModel->getInfoById($astrChatId);
        $d = [
            'reply_num' => Db::raw('reply_num + 1'),
        ];
        if ($nowTimw - $consultChatIdDetail['user_last_msg_time'] < 300)
        {
            $d['min5_reply_num'] = Db::raw('min5_reply_num + 1');
        }
        // 更新回复信息
        (new ZyhsConsultAstrData())->analysisDataUpdate($this->astrInfo['id'], (int)date('YmdH'), $d);
        // 更新用户端 最后咨询信息
        $consultChatIdModel->updateData($userChatId, [
            'uid' => $uid,
            'last_chat_detail_id' => $resData['id'],
            'last_chat_detail_time' => $nowTimw,
            'msg_num' => Db::raw('msg_num + 1'),
        ], $appType);
        $consultChatIdModel->setUserUnreadChatIdMsgNum($appType, $uid, $userChatId, 1, 1);
        $d = [
            'last_chat_detail_id' => $resData['id'],
            'last_chat_detail_time' => $nowTimw,
            'reply_num' => $astrChatIdInfo['reply_num'] + 1,  //  回答总次数
        ];
        if ($astrChatIdInfo['delay_num'] > 0)
        {   // 正常回复消息 数量
            $d['delay_num'] = max($astrChatIdInfo['delay_num'] - 1, 0);  // 待回答数量
        } else
        {   // 消耗连线 增加 回复消息数量
            $d['call_delay_num'] = max($astrChatIdInfo['call_delay_num'] - 1, 0);   // 消耗连线 回复消息数量
        }
        // 更新咨询师端 最后咨询信息
        (new ZyhsConsultChatRecordAstr())->astroSendUpdate($appType, $uid, $this->astrInfo['id'], $d);

        $resData1 = current($consultChatRecordDetailsModel->astrDataListResert([$resData], $this->astrInfo, [], $appType));
        $userData = current($consultChatRecordDetailsModel->userDataListResert([$resData], $this->astrInfo, [], $appType));
        if ($appType === 1)
        {   // 准有 好事
            $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
            $pushModel = new ZyhsPush();
        } else
        {   // 准了APP
            $websocketWho = LiveMessage::WHO_TYPE_UID;
            $pushModel = new Push();
        }
        LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
            'msg_type' => 1,
            'astr_id' => $this->astrInfo['id'],
            'msg_data' => $userData,
        ]);
        if ($nowTimw - $astrChatIdInfo['user_last_msg_time'] < 180)
        {   // 3分钟 以内 回复用户消息
            (new ZlcrAstrConsultActiveReplyRecord())->save(['astr_id' => $this->astrInfo['id'], 'create_time' => $nowTimw]);
        }
        // 向准有好事 用户发送推送消息 --------
        $pushAlert = mb_strlen($content) > 25 ? mb_substr($content, 0, 25) : $content;
        $pushData = [
            'action' => 'extend',
            'target' => 'local',
            'link' => "chat?id={$this->astrInfo['id']}&need_auth=2",
            'pop_msg' => json_encode([
                'avatar' => $this->astrInfo['avatar'],
                'name' => $this->astrInfo['nickname'],
                'level' => $this->consultAccountInfo['level'] ?? 1,
                'msg' => $pushAlert,
                'target' => 'local',
                'link' => "chat?id={$this->astrInfo['id']}&need_auth=2",
                'astr_id' => $this->astrInfo['id'],
            ], JSON_UNESCAPED_UNICODE),
        ];
        $pushModel->pushUserMsg($uid, $pushAlert, $pushData);
        $resData1['time_des'] = '';
        $resData1['intercept_tips'] = $interceptTips ?? '';
        return show(config('code.success'), '请求成功', $resData1);
    }

    /**
     * 回复 咨询问题 答案
     * @return Json
     * @throws \Exception
     */
    public function replayConsultQuestion()
    {
        $id = input('id/d', 0);
        $content = trim(input('content/s', ''));
        $tags = trim(input('tags/s', ''));
        if (!$id || empty($content))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->astrInfo['id'], ['action' => 'replayConsultQuestion', 'id' => $id, 'content' => $content, 'tags' => $tags], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        if (mb_strlen($content) > 200)
        {
            return show(config('code.error'), '最多输入200个字～');
        }

        $res = AliyunFilterWord::checkText($content, 'article_comment');
        // 若内容有违规且超过配置的相似比例，则进行隐藏不显示，将标签存入库中
        if ($res)
        {
            return show(0, '内容涉嫌' . $res['label']);
        }

        $tagsArr = explode(',', $tags);
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($id);

        if (!$chatDetail)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        if (isset($chatDetail['extend']['answer_id']))
        {
            return show(config('code.error'), '问题已经回答过了～');
        }

        $zlcr3ConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
        $astrChatId = $zlcr3ConsultChatRecordAstrModel->getIdByAstrIdAndUid($this->astrInfo['id'], $chatDetail['app_type'], $chatDetail['uid']);
        if (!$astrChatId)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $consultChatIdModel = new ZyhsConsultChatRecord();
        $userChatId = $consultChatIdModel->getChatIdByAstrId($chatDetail['app_type'], $chatDetail['uid'], $this->astrInfo['id']);
        $nowTimw = $this->request->time();
        if (!$userChatId)
        {
            $insertData = [
                'app_type' => $chatDetail['app_type'],
                'uid' => $chatDetail['uid'],
                'astr_id' => $this->astrInfo['id'],
                'last_chat_detail_id' => 0,
                'last_chat_detail_time' => 0,
                'create_time' => $nowTimw,
            ];
            // 创建新的会话
            $userChatId = $consultChatIdModel->SaveData($insertData);
        }

        $consultMsgData = [
            'chat_id' => $userChatId,
            'app_type' => $chatDetail['app_type'],
            'uid' => $chatDetail['uid'],
            'astr_id' => $this->astrInfo['id'],
            'type' => 1,    //  1=>APP消息 2=>用户发送消息
            'title' => '',
            'content' => $content, // 提问问题
            'data_type' => 5,   // 1=>普通消息  2=>图片  3=>语音咨询消息  4=>咨询问题  5=>咨询问题答案
            'extend' => [
                'tags' => $tagsArr,
            ],  //  语音咨询消息 ｜ 图片信息
            'pid' => $id, // 待更新
            'create_time' => $nowTimw,
        ];
        $resData = $consultChatRecordDetailsModel->SaveData($userChatId, $consultMsgData);
        if (!$resData)
        {
            return show(config('code.error'), '服务异常，请稍后再试～');
        }
        $d = [
            'reply_num' => Db::raw('reply_num + 1'),
        ];
        if ($nowTimw - $chatDetail['create_time'] < 300)
        {   // 5分钟内 回复问题
            $d['min5_reply_num'] = Db::raw('min5_reply_num + 1');
        }
        // 更新回复信息
        (new ZyhsConsultAstrData())->analysisDataUpdate($this->astrInfo['id'], (int)date('YmdH'), $d);
        // 更新问题信息
        $chatDetail['extend']['answer_id'] = $resData['id'];
        $consultChatRecordDetailsModel->UpdateData($chatDetail['id'], ['extend' => $chatDetail['extend']]);
        // 更新 咨询问题 信息
        (new ZyhsConsultQuestion())->editData($chatDetail['extend']['cq_id'], $chatDetail['app_type'], $chatDetail['uid'], $this->astrInfo['id'], $resData['id']);
        // 更新用户端 最后咨询信息
        $consultChatIdModel->updateData($userChatId, [
            'uid' => $chatDetail['uid'],
            'last_chat_detail_id' => $resData['id'],
            'last_chat_detail_time' => $nowTimw,
            'msg_num' => Db::raw('msg_num + 1'),
        ], $chatDetail['app_type']);
        $consultChatIdModel->setUserUnreadChatIdMsgNum($chatDetail['app_type'], $chatDetail['uid'], $userChatId, 1, 1);
        $astrChatIdInfo = $zlcr3ConsultChatRecordAstrModel->getInfoById($astrChatId);
        // 更新咨询师端 最后咨询信息
        (new ZyhsConsultChatRecordAstr())->astroSendUpdate($chatDetail['app_type'], $chatDetail['uid'], $this->astrInfo['id'], [
            'last_chat_detail_id' => $resData['id'],
            'last_chat_detail_time' => $nowTimw,
            'reply_num' => $astrChatIdInfo['reply_num'] + 1,  //  回答总次数
        ]);
        $resultData = current($consultChatRecordDetailsModel->astrDataListResert([$resData], $this->astrInfo, [], $chatDetail['app_type']));
        $userData = current($consultChatRecordDetailsModel->userDataListResert([$resData], $this->astrInfo, [], $chatDetail['app_type']));
        if ($chatDetail['app_type'] === 1)
        {   // 准有 好事
            $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
            $pushModel = new ZyhsPush();
        } else
        {   // 准了APP
            $websocketWho = LiveMessage::WHO_TYPE_UID;
            $pushModel = new Push();
        }
        LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $chatDetail['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, [
            'msg_type' => 1,
            'astr_id' => $this->astrInfo['id'],
            'msg_data' => $userData,
        ]);
        // 向准有好事 用户发送推送消息 --------
        $pushAlert = mb_strlen($content) > 25 ? mb_substr($content, 0, 25) : $content;
        $pushData = [
            'action' => 'extend',
            'target' => 'local',
            'link' => "chat?id={$this->astrInfo['id']}&need_auth=2",
            'pop_msg' => json_encode([
                'avatar' => $this->astrInfo['avatar'],
                'name' => $this->astrInfo['nickname'],
                'level' => $this->consultAccountInfo['level'] ?? 1,
                'msg' => $pushAlert,
                'target' => 'local',
                'link' => "chat?id={$this->astrInfo['id']}&need_auth=2",
                'astr_id' => $this->astrInfo['id'],
            ], JSON_UNESCAPED_UNICODE),
        ];
        $pushModel->pushUserMsg($chatDetail['uid'], $pushAlert, $pushData);

        $resultData['time_des'] = '';
        return show(config('code.success'), '请求成功', $resultData);
    }

    /**
     * 接听 连线
     * @return Json
     * @throws \Exception
     */
    public function acceptRtc()
    {
        $chatDetailId = input('id/d', 0);
        if (!$chatDetailId)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        if (Util::commentCheck($this->astrInfo['id'], ['action' => 'acceptRtc', 'id' => $chatDetailId], 5))
        {
            return show(config('code.error'), '操作频繁，请稍后再试～');
        }
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetail)
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $appType = $chatDetail['app_type'] ?? 1;    // 1=>准有好事  2=>准了APP
        // 获取当前用户 咨询状态
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $appType, $this->astrInfo['id']);
        if ($astrNowConsultRtcInfo && (int)$astrNowConsultRtcInfo['chat_id'] === $chatDetailId)
        {
            if ($astrNowConsultRtcInfo['status'] !== 1)
            {
                return show(config('code.error'), '操作失败，连线状态异常～');
            }
            //  rtc操作 加锁  失败则 操作失败
            $res = $consultChatRtcRecordModel->setRtcPadlock($chatDetailId);
            if (!$res)
            {
                return show(config('code.error'), '操作失败，连线状态异常～');
            }
            $uid = (int)$astrNowConsultRtcInfo['uid'];
            // 获取连线用户 咨询状态
            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $appType, $uid);
            if ($userNowConsultRtcInfo && (int)$userNowConsultRtcInfo['chat_id'] === $chatDetailId)
            {
                $aliyunRtcModel = new AliyunRtc();
                $zlcr3ConsultAccountModel = new Zlcr3ConsultAccount();
                $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
                try
                {
                    // 开始事物
                    $consultChatRtcRecordModel->startTrans();
                    $consultAccountInfo = $zlcr3ConsultAccountModel->getInfoById($this->astrInfo['id']);
                    // 用户咨询师 会话信息
                    $consultNum = $zyhsConsultChatRecordAstrModel->getConsultNumByDb($appType, $uid, $this->astrInfo['id']);
                    // $userAstrChatInfo = $zyhsConsultChatRecordAstrModel->getUserAstrChatInfo($appType, $uid, $this->astrInfo['id']);
                    // $serviceNum = ($userAstrChatInfo['consult_num'] ?? 0) + 1;  // 本次服务次数 【 历史已服务次数 + 1 】
                    $serviceNum = $consultNum + 1;  // 本次服务次数 【 历史已服务次数 + 1 】
                    $percent = $zlcr3ConsultAccountModel->getPercent($consultAccountInfo['percent'], $serviceNum);  // 取本次服务 分成比例
                    // 获取新人福利 免充值 发起连线
                    $zyhsConsultRtcUserBenefitsModel = new ZyhsConsultRtcUserBenefits();
                    $newUserWelfare = $zyhsConsultRtcUserBenefitsModel->getConsultRtcUserBenefits($appType, $uid);
                    if ($newUserWelfare)
                    {   // 新人福利 信息
                        $freeRtcDuration = ($newUserWelfare['min'] ?? 0) * 60;
                        $bid = $newUserWelfare['id'] ?? 0;
                    }
                    $rtcData = [
                        'chat_detail_id' => $chatDetailId,
                        'app_type' => $appType,
                        'uid' => $uid,
                        'astr_id' => $this->astrInfo['id'],
                        'status' => 2,  // 2=>连接中 3=>连麦中 4=>连麦结束 5=>停止连麦（未接听） 6=>故障挂断
                        'test_duration' => 60,  //
                        'unit_price' => $consultAccountInfo['price'], // 原价 的 单价
                        'extend' => [
                            'version' => $chatDetail['extend']['version'] ?? '',
                            'percent' => $percent,    // 收益比例
                            'service_num' => $serviceNum,   // 本次服务次数
                            'active_percent' => 1,  // 活动比例
                            'active_id' => 0,  // 活动ID
                            'free_rtc_duration' => $freeRtcDuration ?? 0,   // 免费连线时长
                            'bid' => $bid ?? 0, // 福利ID
                            'gift_id' => (int)($userNowConsultRtcInfo['gift_id'] ?? 0),    // 使用 连线咨询礼包ID
                        ],
                        'create_time' => $astrNowConsultRtcInfo['request_time'],
                    ];

                    $rtcId = $consultChatRtcRecordModel->SaveData($rtcData);
                    if (!$rtcId)
                    {
                        $consultChatRtcRecordModel->rollback();
                        return show(config('code.error'), '服务异常，连线失败～');
                    }
                    $rtcStatusData = [
                        'id' => $rtcId,
                        'status' => 2,
                    ];
                    $consultChatRtcRecordModel->saveNowRtcDataToCache(2, $appType, $this->astrInfo['id'], $rtcStatusData, true, $chatDetailId);
                    $consultChatRtcRecordModel->saveNowRtcDataToCache(1, $appType, $uid, $rtcStatusData, true, $chatDetailId);
                    if (isset($chatDetail['extend']['rtc_data']))
                    {
                        $chatDetail['extend']['rtc_data']['rtc_id'] = $rtcId;
                    } else
                    {
                        $chatDetail['extend']['rtc_data'] = [
                            'rtc_id' => $rtcId,
                            'status' => 1,
                        ];
                    }
                    $consultChatRecordDetailsModel->UpdateData($chatDetailId, [
                        'extend' => $chatDetail['extend'],
                    ]);
                    $subscribeChannelId = 'consult2_' . $chatDetailId;
                    if (!($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小'))
                    {   // 创建订阅回调
                        $subscribeChannelId = 'consult_' . $rtcId;
                        $signToken = ($appType === 1 ? 'zyhs-' : 'zhunle-') . mt_rand(1000, 9999) . '-' . $astrNowConsultRtcInfo['rtc_sign'];
                        $result = $aliyunRtcModel->createEventSubscribe($subscribeChannelId, $signToken, 'consult_subscribe_call_back_url');
                        if ($result['code'] !== 200)
                        {
                            $consultChatRtcRecordModel->rollback();
                            return show(config('code.error'), $result['msg']);
                        }
                        $aliyunRtcModel->RtcStartRecordTask($subscribeChannelId, $subscribeChannelId);
                    }
                    // 提交事物
                    $consultChatRtcRecordModel->commit();
                }
                catch (\Exception $e)
                {
                    \think\Log::write(__CLASS__ . ' => ' . __FUNCTION__ . '()异常：' . $e->getMessage() . '失败信息：' . $e->getFile() . ':' . $e->getLine(), 'error', true);
                    $consultChatRtcRecordModel->rollback();
                    return show(config('code.error'), '服务异常，连线失败～');
                }
                if ($appType === 1)
                {
                    $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
                } else
                {
                    $websocketWho = LiveMessage::WHO_TYPE_UID;
                }
                // 向用户发送 发送消息
                // 1 连麦消息
                $popConsultMsg = [
                    'msg_type' => 1,
                    'astr_id' => $this->astrInfo['id'],
                    'msg_data' => [
                        'id' => $chatDetailId,
                        'type' => 1,
                        'time_des' => '',
                        'time' => '',
                        'avatar' => $astrNowConsultRtcInfo['avatar'],
                        'msg_des' => '连线咨询',
                        'tags' => [],
                        'consult_info' => [
                            'status' => 2,
                            'tip' => '正在接通中',
                            'target' => 'local',
                            'link' => "alert_consult_question?id={$chatDetailId}&need_auth=2",
                        ],
                        'btn_info' => null,
                        'content' => '',
                        'content_type' => 1,
                    ],
                ];
                LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, $popConsultMsg);
                // 2 连麦状态刷新消息
                $consultDetailRefresh = [
                    'target' => 'local',
                    'link' => "alert_consult_question?id={$chatDetailId}&need_auth=2",
                    'force_open' => 1,
                ];
                LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_DETAIL_REFRESH, $consultDetailRefresh);
                // 3 进入Rtc
                if (!($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小'))
                {   // 获取 用户 rtc 授权
                    $userRtcAuth = $aliyunRtcModel->getRtcAuth('user_' . $uid, $subscribeChannelId, 'sub');
                    LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $uid), LiveMessage::MSG_TYPE_POP_CONSULT_RTC_JOIN, $userRtcAuth);
                }
                // 获取 咨询师 rtc 授权
                $astrRtcAuth = $aliyunRtcModel->getRtcAuth('astr_' . $this->astrInfo['id'], $subscribeChannelId, 'pub');
                $resData = [
                    'rtc_auth' => $astrRtcAuth,
                    'msg_data' => [
                        'id' => $chatDetailId,
                        'type' => 2,
                        'time_des' => '',
                        'time' => '',
                        'avatar' => $astrNowConsultRtcInfo['avatar'],
                        'msg_des' => '连线咨询',
                        'tags' => [],
                        'consult_info' => [
                            'status' => 2,
                            'tip' => '正在申请连线咨询',
                            'target' => 'local',
                            'link' => "empty",
                        ],
                        'btn_info' => [
                            [
                                'name' => '连接中',
                                'type' => 5,
                                'id' => 0,
                            ],
                        ],
                        'content' => '',
                        'content_type' => 1,
                    ],
                ];
                $zyhsConsultChatRecordAstrModel = new ZyhsConsultChatRecordAstr();
                $astrChatId = $zyhsConsultChatRecordAstrModel->getIdByAstrIdAndUid($this->astrInfo['id'], $appType, $uid);
                $astrChatIdInfo = $zyhsConsultChatRecordAstrModel->getInfoById($astrChatId);
                $resData['num'] = $astrChatIdInfo['delay_num'] + $astrChatIdInfo['call_delay_num'];

                Util::queuePush('rtc_consult_client_suc_check', ['id' => $chatDetailId, 'rtc_id' => $rtcId], 20);  // 30 秒后进入失败 关闭连线
                return show(config('code.success'), '请求成功', $resData);
            } else
            {   // 用户端 连线信息更新 取消当前连线信息
                $consultChatRtcRecordModel->delNowRtcDataByCache(2, $appType, $this->astrInfo['id'], $chatDetailId);

                $voiceCallData = [
                    'chat_id' => $chatDetailId,
                    'app_type' => $appType,
                    'uid' => $uid,
                    'avatar' => $astrNowConsultRtcInfo['avatar'],
                    'nickname' => $astrNowConsultRtcInfo['nickname'],
                    'status' => 0,
                    'desc' => '',
                ];
                LiveMessage::sendMsg(LiveMessage::who(LiveMessage::WHO_TYPE_ASTRO, 0, $this->astrInfo['id']), LiveMessage::MSG_TYPE_POP_VOICE_CONSULT_CALL, $voiceCallData);

                $consultChatRtcRecordModel->rollback();
                return show(config('code.error'), '连线失败，连线已取消');
            }
        } else
        {
            return show(config('code.error'), '服务异常，连线失败～');
        }
    }

    /**
     * 挂断连线
     * @return Json
     * @throws ApiException
     * @throws \RedisException
     */
    public function refuseRtc()
    {
        $chatDetailId = input('id/d', 0);
        $reason = input('reason/s', '');
        $type = input('type/d', '');    // 1=>拒绝接听 2=>挂断连线

        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();
        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);

        if (!$chatDetail)
        {
            return show(config('code.error'), '连线数据不存在，操作失败');
        }
        $appType = $chatDetail['app_type'] ?? 1;
        $res = $consultChatRtcRecordModel->setRtcPadlock($chatDetailId);
        if (!$res)
        {
            return show(config('code.error'), '连线状态异常，请稍后再试～');
        }

        if ($chatDetail['extend']['rtc_data']['rtc_id'])
        {   // 挂断连线
            if ($type === 1)
            {
                return show(config('code.error'), '连线状态异常，操作失败');
            }
            $resData = $consultChatRtcRecordModel->rtcConsultHangUp($chatDetail, $reason, 2, 1);
            if ($resData['status'])
            {   // 删除 频道订阅 与 当前RTC房间
                if ($appType === 2 && Util::checkAppVersion('2.15.0', $rtcInfo['extend']['version'] ?? '1.0.0') !== '小')
                {
                    (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $chatDetailId);
                } else
                {
                    (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult_' . $chatDetail['extend']['rtc_data']['rtc_id']);
                }
            }

            $consultChatRtcRecordModel->loseOperatorLicense($chatDetailId);
            return show(config('code.success'), '请求成功', $resData['data']);
        } else
        {   // 拒绝接听
            $rtcData = $chatDetail['extend']['rtc_data'] ?? ['rtc_id' => 0, 'status' => -1];
            if ($rtcData['rtc_id'] > 0 || $rtcData['status'] === -1)
            {
                return show(config('code.error'), '连线状态异常，操作失败～');
            }
            if ($rtcData['status'] !== 1)
            {   //  1=>申请中待接听  2=>咨询师未响应  3=>咨询师拒绝  4=>连线已取消 5=>咨询师忙线中
                return show(config('code.error'), '连线已挂断，操作失败');
            }
            if ($appType === 1)
            {   // 准有好事
                $websocketWho = LiveMessage::WHO_TYPE_ZYHS_UID;
                $userInfo = (new ZyhsUser())->getInfoById($chatDetail['uid']);
            } else
            {   // 准了APP
                $websocketWho = LiveMessage::WHO_TYPE_UID;
                $userInfo = (new User())->getUserinfo(['id' => $chatDetail['uid']]);
            }
            $rtcData['status'] = 3;
            $chatDetail['extend']['rtc_data'] = $rtcData;
            // 更新咨询信息状态
            $consultChatRecordDetailsModel->UpdateData($chatDetailId, ['extend' => $chatDetail['extend']]);
            // 删除当前连麦 缓存信息
            $userNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(1, $chatDetail['app_type'], $chatDetail['uid']);
            if ($userNowConsultRtcInfo && $userNowConsultRtcInfo['chat_id'] == $chatDetailId)
            {   // 删除用户当前连麦
                $consultChatRtcRecordModel->delNowRtcDataByCache(1, $chatDetail['app_type'], $chatDetail['uid'], $chatDetailId);
                // 向用户发送 信息
                // 1 连麦消息
                $popConsultMsg = [
                    'msg_type' => 1,
                    'astr_id' => $this->astrInfo['id'],
                    'msg_data' => [
                        'id' => $chatDetailId,
                        'type' => 1,
                        'time_des' => '',
                        'time' => '',
                        'avatar' => $userInfo['avatar'],
                        'msg_des' => '连线咨询',
                        'tags' => [],
                        'consult_info' => [
                            'status' => 4,
                            'tip' => '咨询师不便接听，稍后重试',
                            'target' => 'local',
                            'link' => 'alert_consult_question?id=0&need_auth=2',
                        ],
                        'btn_info' => null,
                        'content' => '',
                        'content_type' => 1,
                    ],
                ];
                LiveMessage::sendMsg(LiveMessage::who($websocketWho, 0, $chatDetail['uid']), LiveMessage::MSG_TYPE_POP_CONSULT_MSG, $popConsultMsg);
            }
            $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $chatDetail['app_type'], $chatDetail['astr_id']);
            if ($astrNowConsultRtcInfo && $astrNowConsultRtcInfo['chat_id'] == $chatDetailId)
            {   // 删除咨询师当前连麦
                $consultChatRtcRecordModel->delNowRtcDataByCache(2, $chatDetail['app_type'], $chatDetail['astr_id'], $chatDetailId);
            }
            $consultChatRtcRecordModel->loseOperatorLicense($chatDetailId);
            // 删除 频道订阅 与 当前RTC房间
            if ($appType === 2 && Util::checkAppVersion('2.15.0', $chatDetail['extend']['version'] ?? '1.0.0') !== '小')
            {
                (new AliyunRtc())->rmEventSubAndDelRtcChannel('consult2_' . $chatDetailId);
            }
            $resData = [
                'id' => $chatDetailId,
                'type' => 2,
                'time_des' => '',
                'time' => '',
                'avatar' => $userInfo['avatar'],
                'msg_des' => '连线咨询',
                'tags' => [],
                'consult_info' => [
                    'status' => 4,
                    'tip' => '咨询师拒绝连线',
                    'target' => 'local',
                    'link' => 'empty',
                ],
                'btn_info' => null,
                'content' => '',
                'content_type' => 1,
            ];
            return show(config('code.success'), '挂断成功', $resData);
        }
    }

    /**
     * 获取 故障挂断 原因
     * @return Json
     */
    public function getCancelReason()
    {
        $data = [
            [
                'id' => 1,
                'name' => '听不见用户声音',
            ], [
                'id' => 2,
                'name' => '用户听不见我的声音',
            ],
            [
                'id' => 3,
                'name' => '用户有杂音',
            ],
            [
                'id' => 4,
                'name' => '我的麦有杂音',
            ],
        ];

        return show(config('code.success'), '请求成功', $data);
    }

    /**
     * 占星师评价列表
     * @return Json
     * @throws \Exception
     */
    public function commentList()
    {
        $list = (new ZyhsConsultChatRtcRecordComment())->astrCommentList($this->astrInfo['id']);
        $res = [];
        $tagsModel = new ZlcrTag();
        foreach ($list['data'] as $item)
        {
            $tagInfo = $tagsModel->batchGetInfoByIds($item['tids'], ['tag_name']);
            $res[] = [
                'name' => $item['name'],
                'avatar' => $item['avatar'],
                'time' => date('Y.m.d H:i', $item['create_time']),
                'tags' => array_column($tagInfo, 'tag_name'),
                'score' => $item['level'],
                'content' => $item['comment'],
            ];
        }
        $list['data'] = $res;
        return show(config('code.success'), 'Success.', $list);
    }

    /**
     * 获取 连线咨询 状态信息
     * @return Json
     * @throws \Exception
     */
    public function getRtcConsultStatusInfo()
    {
        $chatDetailId = input('id/d', 0);

        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        if (!$chatDetail || $chatDetail['astr_id'] !== $this->astrInfo['id'])
        {
            return show(config('code.error'), '请求异常，咨询信息不存在～');
        }
        $appType = $chatDetail['app_type'] ?? 1;
        $astrNowConsultRtcInfo = $consultChatRtcRecordModel->getNowRtcDataByCache(2, $chatDetail['app_type'], $this->astrInfo['id']);
        if ($astrNowConsultRtcInfo && $astrNowConsultRtcInfo['chat_id'] === $chatDetailId)
        {
            $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
            if (!$rtcId)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
            if ($rtcInfo['status'] !== 3)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            if ($appType === 1)
            {
                $user_coin = (new ZyhsUserAccount())->getUserCoinFromCache($astrNowConsultRtcInfo['uid']);  // 账户信息
            } else
            {
                $user_coin = (new ZhunleUserAccount())->getUserCoinFromCache($astrNowConsultRtcInfo['uid']);  // 账户信息
            }
            $giftId = $astrNowConsultRtcInfo['gift_id'] ?? 0;
            $giftDuartion = 0;  // 礼包还可连线时长
            if ($giftId)
            {
                $userGiftInfo = (new AppUserConsultGift())->getInfoById($giftId);
                $giftDuartionMin = $userGiftInfo['duration_minute'] - $userGiftInfo['use_minute'];
                $giftDuartion = $giftDuartionMin * 60;
            }
            $coinNum = (int)($user_coin['balance'] ?? 0);// 准币余额
            $duration = $this->request->time() - $rtcInfo['start_time']; // 当前已连麦时间
            $maxSecond = floor($coinNum / $rtcInfo['unit_price']) * 60; // 消耗准币 还能 连线 多少秒
            // 免费连线时长
            $freeRtcDuration = $rtcInfo['extend']['free_rtc_duration'] ?? 0;
            $freeRtcDuration = max($freeRtcDuration, $rtcInfo['test_duration']); // 免费连线时长 包含试麦时长  取最大值
            // 准币消费 能连线时间 + 付费剩余时间 = 总 最大连线时间 秒
            $s = $duration - $freeRtcDuration; // 付费连线时间
            if ($giftDuartion > $s)
            {   // 礼包使用中
                $s = $giftDuartion - $s;
            } else
            {   // 礼包是用尽 或者 本次连线未使用礼包
                $s = $s - $giftDuartion;
                if ($s > 0)
                {   // 进入正式连麦
                    $s = 60 - ($s % 60);    // 已付费剩余连线时长
                } elseif ($s < 0)
                {   // 试麦中
                    // $s = 60 + $s;
                    $s = $freeRtcDuration - $duration;   // 剩余免费时长 = （免费|试麦）时长 - 当前已连麦时长
                }
            }
            //最大连线时长 =  准币付费连线时长 + 【剩余免费时长｜已付费剩余连线时长】
            $maxSecond = $maxSecond + $s;

            $recodeDatas = $astrNowConsultRtcInfo['recode_datas'] ?? [];
            foreach ($recodeDatas as $k => $recodeItemData)
            {
                $recodeDatas[$k]['comments'] = $recodeItemData['user_des'];
                unset($recodeDatas[$k]['user_des']);
            }

            if ($freeRtcDuration > 0)
            {
                $durationDesc = sprintf("（免费%d分钟）", (int)($freeRtcDuration / 60));
            }

            $resData = [
                'status' => 21,
                'app_type' => $appType,
                'duration' => $duration,
                'duration_desc' => $durationDesc ?? '',
                'test_duration' => $rtcInfo['test_duration'],
                'max_duration' => $maxSecond,
                'dice_datas' => $astrNowConsultRtcInfo['dice_datas'] ?? [],
                'recode_datas' => $recodeDatas,
                'tarot_datas' => $astrNowConsultRtcInfo['tarot_datas'] ?? [],
            ];
        } else
        {
            $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
            if (!$rtcId)
            {
                return show(config('code.error'), '服务异常，请稍后再试～');
            }
            $rtcInfo = $consultChatRtcRecordModel->getInfoById($rtcId);
            if ($rtcInfo['status'] !== 4)
            {
                return show(config('code.error'), '连线状态更新，请刷新后再试～');
            }
            $effDuration = ceil($rtcInfo['eff_duration'] / 60);
            $unitPrice = ceil($rtcInfo['unit_price'] * $rtcInfo['extend']['active_percent']) * $rtcInfo['extend']['percent'] / 10;
            $couponInfoData = null;
            if (isset($rtcInfo['extend']['cid']))
            {
                if ($appType === 1)
                {
                    $userCoupon = (new ZyhsUserCoupon())->getInfoById($rtcInfo['extend']['cid'], ['c_id']);
                    $userCouponAttr = (new ZyhsCoupon())->getInfoById($userCoupon['c_id']);
                } else
                {
                    $userCouponAttr = (new UserCoupon())->getInfoById($rtcInfo['extend']['cid']);
                }
                $desc = "免费{$userCouponAttr['discount']}分钟（优惠券）";
                if ($userCouponAttr['condition'] > 0)
                {
                    $desc = "满{$userCouponAttr['condition']}分钟，" . $desc;
                }
                $couponInfoData = [
                    'title' => '优惠',
                    'des' => $desc,
                    'type' => 1,
                ];
            }
            $resData = [
                'status' => 31,
                'list' => [
                    [
                        'title' => '任务编号',
                        'des' => $chatDetailId,
                        'type' => 2,
                    ], [
                        'title' => '收益单价',
                        'des' => $unitPrice . '元/分钟',
                        'type' => 1,
                    ], [
                        'title' => '连线时长',
                        'des' => Util::secondToMinute($rtcInfo['duration']),
                        'type' => 1,
                    ],
                ],
                'app_type' => $appType,
            ];
            if ($couponInfoData)
            {
                $resData['list'][] = $couponInfoData;
            }
            $resData['list'][] = [
                'title' => '计费时长',
                'des' => $effDuration . '分钟',
                'type' => 1,
            ];
            $resData['list'][] = [
                'title' => '连线收益',
                'des' => $rtcInfo['astr_earning'] . '元',
                'type' => 1,
            ];
            $resData['list'][] = [
                'title' => '客户来源',
                'des' => $appType === 1 ? '准有好事' : '准了',
                'type' => 1,
            ];
        }
        return show(config('code.success'), '请求成功', $resData);
    }

    /**
     * 获取连线历史任务列表
     * @return Json
     * @throws DbException
     */
    public function getConsultTaskList()
    {
//        $page = input('page/d', 1);
        $appType = input('app_type/d', 1);
        if (!in_array($appType, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }
        $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
        $pageData = $consultChatRtcRecordModel->where(['astr_id' => $this->astrInfo['id'], 'status' => 4, 'app_type' => $appType])
            ->order('id desc')->field('id,app_type,is_recommend,chat_detail_id,is_comment,duration,test_duration,eff_duration,unit_price,astr_earning,extend,end_time')->paginate()->toArray();

        $pageData['data'] = $consultChatRtcRecordModel->dataInit($pageData['data']);

        $dataList = [];
        $consultChatRtcRecordCommentModel = new ZyhsConsultChatRtcRecordComment();
        $zyhsUserCouponModel = new ZyhsUserCoupon();
        $zyhsCouponModel = new ZyhsCoupon();
        $userCouponModel = new UserCoupon();
        foreach ($pageData['data'] as $datum)
        {
            $commintDes = '未评价';
            if ($datum['is_comment'])
            {
                $level = $consultChatRtcRecordCommentModel->where('rtc_id', $datum['id'])->value('level');
                $commintDes = $level . '星';
            }
            $unit = $datum['unit_price'] / 10 * ($datum['extend']['percent'] ?? 0);
            $couponInfoStr = '';
            if (isset($datum['extend']['cid']))
            {
                if ((int)$datum['app_type'] === 1)
                {
                    $userCoupon = $zyhsUserCouponModel->getInfoById($datum['extend']['cid'], ['c_id']);
                    $userCouponAttr = $zyhsCouponModel->getInfoById($userCoupon['c_id']);
                } else
                {
                    $userCouponAttr = $userCouponModel->getInfoById($datum['extend']['cid']);
                }
                $couponInfoStr = "免费{$userCouponAttr['discount']}分钟（优惠券）";
                if ($userCouponAttr['condition'] > 0)
                {
                    $couponInfoStr = "满{$userCouponAttr['condition']}分钟，" . $couponInfoStr;
                }
                $couponInfoStr = "优惠：" . $couponInfoStr;
            }
            $rtcBenefitsStr = '';
            if (isset($datum['extend']['free_rtc_duration']) && $datum['extend']['free_rtc_duration'] > $datum['test_duration'])
            {   // 连线福利
                $rtcBenefitsStr = sprintf("新人优惠：免费%d分钟", (int)($datum['extend']['free_rtc_duration'] / 60));
            }
            $resItem = [
                'title' => '连线咨询',
                'status_des' => '已完成',
                'list' => [
                    '任务编号：' . $datum['chat_detail_id'],
                    '计价时长：' . Util::secondToMinute($datum['eff_duration']),
                ],
                'id' => $datum['chat_detail_id'],
            ];
            if ($couponInfoStr)
            {
                $resItem['list'][] = $couponInfoStr;
            }
            if ($rtcBenefitsStr)
            {
                $resItem['list'][] = $rtcBenefitsStr;
            }
            $resItem['list'][] = '连线时长：' . Util::secondToMinute($datum['duration']);
            $resItem['list'][] = "收益单价：{$unit}元/分钟";
            $resItem['list'][] = "税前收益：{$datum['astr_earning']}元";

            $serviceNum = $datum['extend']['service_num'] ?? 1;
            switch (true)
            {
                case $serviceNum >= 2 && $serviceNum <= 5:
                    $userType = '复购（咨询次数≥2次且≤5次）';
                    break;
                case $serviceNum > 5 && $serviceNum <= 10:
                    $userType = '复购（咨询次数≥6次且≤10次）';
                    break;
                case $serviceNum > 10:
                    $userType = '复购（咨询次数≥11次）';
                    break;
                default:
                    $userType = '普通用户';
            }
            $resItem['list'][] = '客户类型：' . $userType;
            $percent = $datum['extend']['percent'] * 100;
            $resItem['list'][] = "分成比例：{$percent}%";

            $resItem['list'][] = '评价状态：' . $commintDes;
            $resItem['list'][] = '是否被推荐：' . ($datum['is_recommend'] ? '是' : '否');
            $resItem['list'][] = '完成时间：' . date('Y-m-d H:i:s', $datum['end_time']);

            $teamId = $datum['extend']['team_id'] ?? 0;
            $resItem['list'][] = '结算类型：' . ($teamId > 0 ? '团队结算' : '个人结算');

            $dataList[] = $resItem;
        }

        $pageData['data'] = $dataList;
        return show(config('code.success'), '请求成功', $pageData);
    }

    /**
     * 获取当前正在连麦的任务
     * @return Json
     */
    public function getConsultTaskCurrent(): Json
    {
        $data = ['id' => 0, 'create_time' => 0];
        try
        {
            $consultChatRtcRecordModel = new ZyhsConsultChatRtcRecord();
            $dataDb = $consultChatRtcRecordModel->where(['astr_id' => $this->astrInfo['id']])->order('id desc')->findOrFail()->toArray();
            if ((int)$dataDb['status'] == 3)
            {
                $data['id'] = $dataDb['chat_detail_id'];
                $data['create_time'] = $dataDb['create_time'];
            }
        }
        catch (Exception $e)
        {
        }
        return show(config('code.success'), '请求成功', $data);
    }

    public function rtcChatDetail()
    {
        $chatDetailId = input('id/d', 0);
        $consultChatRecordDetailsModel = new ZyhsConsultChatRecordDetails();

        $chatDetail = $consultChatRecordDetailsModel->getInfoById($chatDetailId);
        $rtcId = $chatDetail['extend']['rtc_data']['rtc_id'] ?? 0;
        if (!$chatDetail || $chatDetail['astr_id'] !== $this->astrInfo['id'] || !$rtcId)
        {
            return show(config('code.error'), '服务异常，咨询信息不存在～');
        }
        $data = (new ZyhsConsultChatRtcRecord)->getInfoById($rtcId);
        $comment = $data['is_comment'] ? (new ZyhsConsultChatRtcRecordComment())->getInfoById($data['id'], ['level']) : null;

        $couponInfoData = null;
        if (isset($data['extend']['cid']))
        {
            if ($data['app_type'] === 1)
            {
                $userCoupon = (new ZyhsUserCoupon())->getInfoById($data['extend']['cid'], ['c_id']);
                $userCouponAttr = (new ZyhsCoupon())->getInfoById($userCoupon['c_id']);
            } else
            {
                $userCouponAttr = (new UserCoupon())->getInfoById($data['extend']['cid']);
            }
            $desc = "免费{$userCouponAttr['discount']}分钟（优惠券）";
            if ($userCouponAttr['condition'] > 0)
            {
                $desc = "满{$userCouponAttr['condition']}分钟，" . $desc;
            }
            $couponInfoData = [
                'title' => '优惠',
                'des' => $desc,
                'type' => 1,
            ];
        }
        // 连线福利【新人福利】
        $rtcBenefits = null;
        if (isset($data['extend']['free_rtc_duration']) && $data['extend']['free_rtc_duration'] > $data['test_duration'])
        {   // 连线福利
            $rtcBenefits = [
                'title' => '新人优惠',
                'des' => sprintf("免费%d分钟", (int)($data['extend']['free_rtc_duration'] / 60)),
                'type' => 1,
            ];
        }

        $res = [
            'title' => '本次消耗详情',
            'list' => [
                [
                    'title' => '任务编号',
                    'des' => $data['chat_detail_id'] ?? 0,
                    'type' => 2,
                ],
            ],
        ];

        if (!isset($data['extend']['gift_id']) || !isset($data['extend']['gift_use_duration']) || !$data['extend']['gift_id'] || !$data['extend']['gift_use_duration'])
        {   // 未使用 礼包
            $res['list'][] = [
                'title' => '收益单价',
                'des' => (ceil($data['unit_price'] * $data['extend']['active_percent']) * $data['extend']['percent'] / 10) . '元/分钟',
                'type' => 1,
            ];
        }
        $res['list'][] = [
            'title' => '连线时长',
            'des' => gmdate("H:i:s", $data['duration']),
            'type' => 1,
        ];
        if ($couponInfoData)
        {   // 优惠券信息
            $res['list'][] = $couponInfoData;
        }
        if ($rtcBenefits)
        {   // 连线福利
            $res['list'][] = $rtcBenefits;
        }
        if (isset($data['extend']['gift_id'], $data['extend']['gift_use_duration']) && $data['extend']['gift_id'] > 0 && $data['extend']['gift_use_duration'] > 0)
        {   // 连线 使用礼包
            $userGiftInfo = (new AppUserConsultGift())->getInfoById($data['extend']['gift_id'], ['gift_id', 'unit_price']);
            $giftInfo = (new AppConsultGift())->getInfoById($userGiftInfo['gift_id'], ['name']);
            $res['list'][] = [
                'title' => '礼包',
                'des' => $giftInfo['name'],
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '礼包计费时长',
                'des' => ceil($data['extend']['gift_use_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '礼包收益单价',
                'des' => sprintf('%s元/分钟', ($userGiftInfo['unit_price'] * $data['extend']['percent']) / 10),
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '超出礼包时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
            $res['list'][] = [
                'title' => '超出礼包单价',
                'des' => (ceil($data['unit_price'] * $data['extend']['active_percent']) * $data['extend']['percent'] / 10) . '元/分钟',
                'type' => 1,
            ];
        } else
        {
            $res['list'][] = [
                'title' => '计费时长',
                'des' => ceil($data['eff_duration'] / 60) . '分钟',
                'type' => 1,
            ];
        }
        $res['list'][] = [
            'title' => '收益',
            'des' => $data['astr_earning'] . '元',
            'type' => 1,
        ];
        if ($data['is_comment'])
        {
            $res['list'][] = [
                'title' => '评价',
                'des' => $comment['level'],
                'type' => 3,
            ];
        }
        if ($data['is_recommend'] === 1)
        {
            $res['list'][] = [
                'title' => '推荐',
                'des' => '已推荐',
                'type' => 1,
            ];
        }
        $res['list'][] = [
            'title' => '客户来源',
            'des' => $data['app_type'] === 1 ? '准有好事' : '准了',
            'type' => 1,
        ];

        return show(config('code.success'), '请求成功', $res);
    }

    /**
     * 咨询师排行榜
     */
    public function getRankingList()
    {
        $type = input('type/d', 0);
        if (!in_array($type, [1, 2], true))
        {
            return show(config('code.error'), '请求异常，请稍后再试～');
        }

        $data = (new ZyhsConsultAstrData())->getRankingList($type);

        if ($type === 1)
        {
            $i = 60 - date('i');
            $tip = "根据咨询师的专业值排名，{$i}分钟后刷新";
        } else
        {
            $i = 10 - (date('i') % 10);
            $tip = "根据咨询师的热度排序，{$i}分钟后刷新";
        }

        $resData = [
            'tip' => $tip,
            'url' => Env::get('host.domain') . '/web/consult_chat/rankrule.html?type=' . $type,
            'data' => (new Zlcr3ConsultAccount())->rankingData($data),
        ];

        return show(config('code.success'), '请求成功', $resData);
    }
}
